package com.hyt.it.ogt.ks.controller;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.hyt.it.ogt.ks.model.vo.paper.FilePicAnswerVO;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.common.apiInfor.DataType;
import com.hyt.common.apiInfor.ParamType;
import com.hyt.it.ogt.ks.config.KsBizRunTimeException;
import com.hyt.it.ogt.ks.enums.BizStatusCode;
import com.hyt.it.ogt.ks.model.entity.mongodb.CandidateAnswerLogBackup;
import com.hyt.it.ogt.ks.model.vo.FileItemVO;
import com.hyt.it.ogt.ks.model.vo.paper.FileItemInfo;
import com.hyt.it.ogt.ks.service.IFileItemService;
import com.hyt.it.ogt.ks.service.Event.CandidateAnswerLogEvent;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "22.文件题接口", value = "文件题接口")
@ApiSort(22)
@Slf4j
@RestController
@RequestMapping("/ks/fileItem/")
public class FileItemController {
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;
    @Resource
    private IFileItemService iFileItemService;


    @ApiOperation(value = "22.1 保存文件题答案", notes = "异常码：41220101-上传的答案文件超过最大限制,41220102-上传的文件非当前题," +
            "41220103-上传的文件参数不正确,41220104-文件保存失败,41220105-考生已交卷，不允许上传文件")
    @ApiOperationSort(1)
    @PostMapping("add")
    public ApiResponse add(@RequestBody @Valid FileItemVO FileItemVO, BindingResult bindingResult) {
        log.info("上传答案fileItemUpload：{}", JSON.toJSONString(FileItemVO));
        try {
            CandidateAnswerLogBackup logBackup = CandidateAnswerLogBackup.builder().examId(FileItemVO.getExamId()).candidateId(FileItemVO.getCandidateId())
                    .paperSort(FileItemVO.getPaperSort()).createDate(LocalDateTime.now()).requestJson(JSON.toJSONString(FileItemVO)).build();
            applicationEventPublisher.publishEvent(new CandidateAnswerLogEvent(logBackup, null));
        } catch (Exception e) {
            log.error("保存答案失败saveQuestion:{}", e.getMessage());
        }
        try {
            if (bindingResult.hasErrors()) {
                log.info("上传答案fileItemUpload参数错误:", bindingResult.getAllErrors());
                return ApiResponse.builder().code(BizStatusCode.FILE_ANSWER_ITEM_UPLOAD_PARAM_WRONG.getCode())
                        .data(bindingResult.getAllErrors()).build();
            }
            iFileItemService.add(FileItemVO);
        } catch (KsBizRunTimeException e) {
            return ApiResponse.builder().code(e.getCode()).data(e.getMessage()).build();
        } catch (Exception e) {
            log.error("", e);
            return ApiResponse.builder().code(BizStatusCode.FILE_ANSWER_ITEM_UPLOAD_ERROR.getCode())
                    .data(BizStatusCode.FILE_ANSWER_ITEM_UPLOAD_ERROR.getMsg()).build();
        }
        return ApiResponse.builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).build();
    }

    @ApiOperation(value = "22.2 获取题答案")
    @ApiOperationSort(2)
    @GetMapping("get")
    public ApiResponse<FilePicAnswerVO> get(@RequestParam String examId, @RequestParam String candidateId,
                                            @RequestParam Integer paperSort, @RequestParam String itemId) {
        FilePicAnswerVO fileList = iFileItemService.get(examId, candidateId, paperSort, itemId);
        log.info("获取小题答案fileItemGet：{},{},{},{}", examId, candidateId, paperSort, itemId);
        return ApiResponse.<FilePicAnswerVO>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).data(fileList).build();
    }

    @ApiOperation(value = "22.3 删除答案", notes = "41210301:考生已交卷，不允许删除")
    @ApiOperationSort(3)
    @DeleteMapping("del")
    public ApiResponse del(@RequestParam String examId, @RequestParam String candidateId, @RequestParam Integer paperSort,
                           @RequestParam String itemId, @RequestParam String fileUrl, HttpServletRequest request) {
        log.info("删除小题文件fileItemDel：{},{},{},{}", examId, candidateId, paperSort, itemId, fileUrl);

        iFileItemService.del(examId, candidateId, paperSort, itemId, fileUrl,request);
        return ApiResponse.builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).build();
    }

    @ApiOperation(value = "22.4 获取题信息", response = FileItemInfo.class)
    @ApiOperationSort(4)
    @GetMapping("getItemInfo")
    public ApiResponse<FileItemInfo> getItemContent(@RequestParam String examId, @RequestParam String candidateId, @RequestParam Integer paperSort,
                                                    @RequestParam String itemId) {
        log.info("获取小题题干fileItemGetItemContent：{},{},{},{}", examId, candidateId, paperSort, itemId);
        FileItemInfo data = iFileItemService.getItemInfo(examId, candidateId, paperSort, itemId);
        return ApiResponse.<FileItemInfo>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).data(data).build();
    }

    @ApiOperation(value = "22.5 获取文件数量限制上线", notes = "limitNum:上传文件数量限制，fileMaxSize：单个文件大小限制（单位MB）")
    @ApiImplicitParams({@ApiImplicitParam(name = "type", value = "audio-音视频题，attachment-附加题", dataType = DataType.STRING,
            paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(5)
    @GetMapping("getLimitNum")
    public ApiResponse<Map<String, Object>> getLimitNum(@RequestParam String type) {
        Map<String, Object> data = new HashMap<>();
        int limit = iFileItemService.getLimitByType(type);
        int fileMaxSize = iFileItemService.getFileMaxSizeByType(type);
        data.put("limitNum", limit);
        data.put("fileMaxSize", fileMaxSize);
        return ApiResponse.<Map<String, Object>>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).data(data).build();
    }

    @ApiOperation(value = "22.6 是否允许上传文件（达到上线不允许传）", notes = "返回Boolean值")
    @ApiImplicitParams({@ApiImplicitParam(name = "type", value = "audio-音视频题，attachment-附加题", dataType = DataType.STRING,
            paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(6)
    @GetMapping("allowUpload")
    public ApiResponse<Boolean> allowUpload(@RequestParam String examId, @RequestParam String candidateId, @RequestParam Integer paperSort,
                                            @RequestParam String itemId, @RequestParam String type) {
        boolean flag = iFileItemService.allowUpload(examId, candidateId, paperSort, itemId, type);
        return ApiResponse.<Boolean>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).data(flag).build();
    }
}
